package main;
import java.io.IOException;

import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.connection.ChannelState;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.util.InvalidStateException;

public class ShhConnector {
	String username;
	String hostname;
	String password;
	int timeout;

	public ShhConnector(String host, String user, String pass, int tout) {
		hostname = host;
		username = user;
		password = pass;
		timeout = tout;
	}

	public String executeCmd(String cmd) {
		SshClient ssh = new SshClient();
		String theOutput = null;

		try {
			ssh.connect(hostname);
			PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
			pwd.setUsername(username);
			pwd.setPassword(password);
			int result = ssh.authenticate(pwd);
			if (result == AuthenticationProtocolState.COMPLETE) {
				SessionChannelClient sessionCh = ssh.openSessionChannel();
				ChannelClientInputStream inputStream = new ChannelClientInputStream(
						sessionCh, timeout);
				if (sessionCh.executeCommand(cmd)) {
					// wait until all the data arrives

					sessionCh.getState().waitForState(
							ChannelState.CHANNEL_CLOSED, timeout);
					theOutput = new String(inputStream.getAllDataFromBuffers());
				}
				ssh.disconnect();

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return theOutput;

	}

}
